package com.aaa.jwt;

import io.jsonwebtoken.*;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtils {
    private static final String ISS="aaa";//jwt签发者
    private static  final long EXP=1000*60*60L;//jwt的过期时间，默认1小时
    private static  final  String SECRET="JAVA";//密钥
    public static String getToken(Authentication authentication) {
        HashMap<String,Object>claims=new HashMap<>();
        claims.put("auth",authentication);
        //权限
        JwtBuilder builder = Jwts.builder()

                //发布者
                .setIssuer(ISS)
                //加密方式
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setId("1001")
                //超时时间
                .setExpiration(new Date(System.currentTimeMillis() + EXP))
                //发布时间
                .setIssuedAt(new Date());
//                //主要信息
//                .claim("msg", "aaa")
//                .compact();
         String token =builder.addClaims(claims).compact();
      return token;
    }
    public static Claims getToken(String token){
        Jws<Claims>jws=Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        return jws.getBody();
    }
    //判断token是否过期
public static  boolean isExpiration(Claims claims){
    Date expiration=claims.getExpiration();
    Date now= new Date();
    if(now.getTime()-expiration.getTime()>0) {
        return false;
    }else {
        return true;
    }
    }
    public static  Map getAuth(Claims claims){
     Map auth= (Map) claims.get("auth");
     return auth;
    }
}
